package com.tlvip.design.singleton.enumSingleton;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * <p>description：</p>
 * <p>copyright： copyright(C)2016-2099</p>
 * <p>Life is short,we need passion</p>
 * <p>Summary： </p>
 * <p>instructions： </p>
 * Date 2021/8/15</p>
 * Author mac
 *
 * @version 1.0
 */
public enum EnumSingleton {
    INSTANCE;

    public void print() {
        System.out.println(this.hashCode());
    }
}

class EnumTest {
    public static void main(String[] args) {
//        try {
//            Constructor<EnumSingleton> declaredConstructor = EnumSingleton.class
//                    .getDeclaredConstructor(String.class, int.class);
//            declaredConstructor.setAccessible(true);
//            // 传两个参数的原因是由于jvm帮我们将enum继承了Enum(String name, int ordinal) 通过javap -p -v 获知
//            // 这里报错，标明了enum是线程安全且不会受反射攻击
//            declaredConstructor.newInstance("INSTANCE", 0);
//        } catch (NoSuchMethodException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }

//        testObjectToDisk();

        testObjectFromDisc();

    }

//    private static void testObjectToDisk() {
//        EnumSingleton instance = EnumSingleton.INSTANCE;
//        try {
//            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("enumSingleton"));
//            oos.writeObject(instance);
//            oos.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    private static void testObjectFromDisc() {
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("enumSingleton"));
            EnumSingleton instance = (EnumSingleton) ois.readObject();

            // true 枚举类型是天然支持序列化的
            System.out.println(instance == EnumSingleton.INSTANCE);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
